<template>
<div class="login">
  <div class="login_box">
    <h1>登陆的页面</h1>
    <el-form label-width="50px" :model="userForm">
      <el-form-item label="账 号">
        <el-input placeholder="请输入账号" v-model="userForm.username" size="small" prefix-icon="el-icon-user-solid"  ></el-input>
      </el-form-item>
      <el-form-item label="密 码">
        <el-input placeholder="请输入密码" size="small" prefix-icon="el-icon-view" show-password v-model="userForm.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="login"><i  v-if="loading" class="el-icon-loading"></i> 登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</div>
</template>

<script>
export default {
  name: 'index',
  data () {
    return {
      userForm: {
        username: 'admin',
        password: '123456'
      },
      //  登录的加载
      loading: false,
      // 跳转的地址
      redirect: undefined,
      otherQuery: {}
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  methods: {
    // 登录
    login () {
      this.loading = true
      this.$store.dispatch('user/login', this.userForm).then(() => {
        this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    getOtherQuery (query) {
      return Object.keys(query).reduce((acc, cur) => {
        // console.log(acc, cur)
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>

<style scoped lang="scss">
.login {
  width: 100%;
  height: 100%;
  background: #2c3e50;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  .login_box {
    width: 500px;
    height: 300px;
    padding: 0 20px;
  }
  h1 {
    color: aliceblue;
  }
}
</style>
